import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class CustomPaintPage extends StatelessWidget {
  const CustomPaintPage({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(appBar: AppBar(title:const Text('CustomPaintPage')),
        body:Center(child: CustomPaint(
          size: const Size(200, 200), // 设置画布大小
          painter: SmileFacePainter(), // 背景绘制器
          foregroundPainter: SmileFaceBorderPainter(), // 前景绘制器（额外层）
          isComplex: true, // 是否复杂图形（优化性能相关）
          willChange: false, // 是否频繁重绘（优化缓存）
          child: const SizedBox(width: 200, height: 200), // 保证大小一致
        ))
    );
  }
}
class SmileFacePainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    final center = Offset(size.width / 2, size.height / 2);
    final radius = size.width / 2;

    final paint = Paint()
      ..color = Colors.yellow
      ..style = PaintingStyle.fill;

    // 绘制圆形脸部
    canvas.drawCircle(center, radius, paint);

    // 眼睛
    final eyePaint = Paint()..color = Colors.black;
    final eyeRadius = size.width * 0.06;

    final leftEye = Offset(size.width * 0.35, size.height * 0.35);
    final rightEye = Offset(size.width * 0.65, size.height * 0.35);
    canvas.drawCircle(leftEye, eyeRadius, eyePaint);
    canvas.drawCircle(rightEye, eyeRadius, eyePaint);

    // 嘴巴（弧线）
    final mouthRect = Rect.fromCenter(
      center: Offset(size.width / 2, size.height * 0.65),
      width: size.width * 0.5,
      height: size.height * 0.3,
    );

    final mouthPaint = Paint()
      ..color = Colors.black
      ..style = PaintingStyle.stroke
      ..strokeWidth = 4;

    canvas.drawArc(mouthRect, 0, 3.14, false, mouthPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) {
    // 如果绘制逻辑可能变化，返回 true
    return false;
  }
}

class SmileFaceBorderPainter extends CustomPainter {
  @override
  void paint(Canvas canvas, Size size) {
    // 画一个灰色边框圈，作为前景层演示
    final borderPaint = Paint()
      ..color = Colors.grey
      ..style = PaintingStyle.stroke
      ..strokeWidth = 2;

    canvas.drawCircle(Offset(size.width / 2, size.height / 2),
        size.width / 2 + 1, borderPaint);
  }

  @override
  bool shouldRepaint(covariant CustomPainter oldDelegate) => false;
}
